package de.homelabs.jaxbsandbox;

import java.io.FileOutputStream;
import java.util.regex.Pattern;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.xml.sax.SAXException;

public class CDataContentHandler extends XMLSerializer {
	  // see http://www.w3.org/TR/xml/#syntax
	  private static final Pattern XML_CHARS = Pattern.compile("[<>&]");

	  public CDataContentHandler(FileOutputStream fileOutputStream, OutputFormat format) {
		super(fileOutputStream, format);
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
	    boolean useCData = XML_CHARS.matcher(new String(ch,start,length)).find();
	    if (useCData) super.startCDATA();
	    super.characters(ch, start, length);
	    if (useCData) super.endCDATA();
	  }

	}
